#!/usr/local/bin/node

var ivsi_dir = '/usr/local/ivsi/';
var path = require('path');
var bin_name = path.basename(__filename);
var assert = require('assert');
var fs = require('fs');
var sync = require('child_process').spawnSync;
var syslog = require(ivsi_dir + 'lib/node_modules/modern-syslog');
var bunyan = require(ivsi_dir + 'lib/node_modules/bunyan');
var consul_t_bin = ivsi_dir + 'bin/consul-template';
var ntp_bin = ivsi_dir + 'script/config_ntp.sh';
var consul_conf_t = ivsi_dir + 'template/ivsi_consul.json.ctmpl';
var consul_conf = ivsi_dir + 'conf/consul/ivsi_consul_dynamic.json';
var consulr_conf_t = ivsi_dir + 'template/ivsi_consul_replicate.conf.ctmpl';
var consulr_conf = ivsi_dir + 'conf/consul-replicate/ivsi_consul_replicate.conf';

var log = bunyan.createLogger({
    name: bin_name,
    streams: [{
        path: '/var/log/vrcm/errorlog/' + bin_name + '.log',
        // `type: 'file'` is implied
    }]
});

syslog.open(bin_name, syslog.LOG_PID | syslog.LOG_ODELAY, syslog.LOG_LOCAL0);

if (process.argv.indexOf("-f") == -1) {
  console.log("need args");
  log.error("need args");
  syslog.log(syslog.LOG_ERR, "need args");
  process.exitCode = 1;
  return;
}

var file = process.argv[process.argv.indexOf("-f") + 1]; //grab the next item

if (!file) {
  console.log("need args");
  log.error("need args");
  syslog.log(syslog.LOG_ERR, "need args");
  process.exitCode = 1;
  return;
}

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    log.error('Error: ' + err);
    syslog.log(syslog.LOG_ERR, "Error: " + err);
    process.exitCode = 1;
    return;
  }

  try {
    data = JSON.parse(data);
  } catch (err) {
    console.log("failed to parse conf: " + file + ", error: " + err);
    log.error("failed to parse conf: " + file + ", error: " + err);
    syslog.log(syslog.LOG_ERR, "failed to parse conf: " + file + ", error: " + err);
    process.exitCode = 1;
    return;
  }

});
